<?php

namespace aerovuelos\UsuarioBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;
use aerovuelos\UsuarioBundle\Entity\Usuarios;
use aerovuelos\UsuarioBundle\Form\UsuariosType;

/**
 * Usuarios controller.
 *
 */
class UsuariosController extends Controller {

    public function loginAction() {

        $request = $this->getRequest();
        $session = $request->getSession();


        if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
            $error = $request->attributes->get(
                    SecurityContext::AUTHENTICATION_ERROR
            );
        } else {
            $error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
            $session->remove(SecurityContext::AUTHENTICATION_ERROR);
        }

        return $this->render('UsuarioBundle:Usuarios:login.html.twig', array(
                    // last username entered by the user
                    'last_username' => $session->get(SecurityContext::LAST_USERNAME),
                    'error' => $error
                        )
        );
    }

    public function loginBoxAction($id = '') {
        $usuario = $this->get('security.context')->getToken()->getUser();

        return $this->render('UsuarioBundle:Usuarios:loginBox.html.twig', array(
                    'usuario' => $usuario
        ));
    }

    public function homeAction() {
        return $this->render('UsuarioBundle:Usuarios:home.html.twig');
    }

    /**
     * Lists all Usuarios entities.
     *
     */
    public function indexAction() {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('UsuarioBundle:Usuarios')->findAll();
        
        return $this->render('UsuarioBundle:Usuarios:index.html.twig', array(
                    'entities' => $entities, 
                    
        ));
    }

    /**
     * Creates a new Usuarios entity.
     *
     */
    public function createAction(Request $request) {
        $usuario = new Usuarios();
        $form = $this->createForm(new UsuariosType(), $usuario);

        if ($request->getMethod() == 'POST') {
            $form->bind($request);

            if ($form->isValid()) {
                $em = $this->getDoctrine()->getManager();

                // Completar las propiedades que el usuario no rellena en el formulario
                $usuario->setSalt(md5(time()));

                $encoder = $this->get('security.encoder_factory')->getEncoder($usuario);
                $passwordCodificado = $encoder->encodePassword(
                        $usuario->getPassword(), $usuario->getSalt()
                );
                $usuario->setPassword($passwordCodificado);

                $em->persist($usuario);
                $em->flush();

                return $this->redirect($this->generateUrl('usuarios'));
            }
        }
        return $this->render('UsuarioBundle:Usuarios:new.html.twig', array(
                    'entity' => $usuario,
                    'form' => $form->createView(),
        ));
    }

    /**
     * Displays a form to create a new Usuarios entity.
     *
     */
    public function newAction() {
        $entity = new Usuarios();
        $form = $this->createForm(new UsuariosType(), $entity);

        return $this->render('UsuarioBundle:Usuarios:new.html.twig', array(
                    'entity' => $entity,
                    'form' => $form->createView(),
        ));
    }

    /**
     * Finds and displays a Usuarios entity.
     *
     */
    public function showAction($id) {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('UsuarioBundle:Usuarios')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Usuarios entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return $this->render('UsuarioBundle:Usuarios:show.html.twig', array(
                    'entity' => $entity,
                    'delete_form' => $deleteForm->createView(),));
    }

    /**
     * Displays a form to edit an existing Usuarios entity.
     *
     */
    public function editAction($id) {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('UsuarioBundle:Usuarios')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Usuarios entity.');
        }

        $editForm = $this->createForm(new UsuariosType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        return $this->render('UsuarioBundle:Usuarios:edit.html.twig', array(
                    'entity' => $entity,
                    'edit_form' => $editForm->createView(),
                    'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Edits an existing Usuarios entity.
     *
     */
    public function updateAction(Request $request, $id) {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('UsuarioBundle:Usuarios')->find($id);

        $password = $entity->getPassword();

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Usuarios entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createForm(new UsuariosType(), $entity);
        $editForm->bind($request);

        if ($editForm->isValid()) {

            if ($editForm->get('password')->getData() != '') {
                $entity->setSalt(md5(time()));

                $encoder = $this->get('security.encoder_factory')->getEncoder($entity);
                $passwordCodificado = $encoder->encodePassword(
                        $entity->getPassword(), $entity->getSalt()
                );
                $entity->setPassword($passwordCodificado);
            } else {
                $entity->setPassword($password);
            }

            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('usuarios'));
        }

        return $this->render('UsuarioBundle:Usuarios:edit.html.twig', array(
                    'entity' => $entity,
                    'edit_form' => $editForm->createView(),
                    'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Deletes a Usuarios entity.
     *
     */
    public function deleteAction(Request $request, $id) {
        $form = $this->createDeleteForm($id);
        $form->bind($request);

        if ($form->isValid()) {
            try {
                $em = $this->getDoctrine()->getManager();
                $entity = $em->getRepository('UsuarioBundle:Usuarios')->find($id);

                if (!$entity) {
                    throw $this->createNotFoundException('Unable to find Usuarios entity.');
                }

                $em->remove($entity);
                $em->flush();
            } catch (\Doctrine\DBAL\DBALException $e) {
                return $this->redirect($this->generateUrl('usuarios_edit', array(
                                    'id' => $id,
                                    'error' => '1'
                )));
            }
        }

        return $this->redirect($this->generateUrl('usuarios'));
    }
    

    /**
     * Creates a form to delete a Usuarios entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id) {
        return $this->createFormBuilder(array('id' => $id))
                        ->add('id', 'hidden')
                        ->getForm()
        ;
    }

}
